import { CLOUD_CONFIG } from '../../cloud-config.js'

export default class CloudManager {
  constructor() {
    this.db = null
    this.roomId = null
    this.playerId = null
    this.isCreator = false
    this.roomWatcher = null
    this.gameStarted = false
    this.periodicCheckTimer = null
    this.pollingTimer = null
    this.watchRetryCount = 0
    this.maxWatchRetries = 5
    this.cachedOpenId = null // 缓存OpenID，确保同一用户使用相同ID
    
    // 回调函数
    this.onRoomCreated = null
    this.onRoomJoined = null
    this.onGameStart = null
    this.onMoveReceived = null
    this.onGameOver = null
    this.onOpponentConnected = null
    this.onOpponentDisconnected = null
    
    this.initCloud()
  }

  // 初始化云开发
  async initCloud() {
    try {
      if (typeof wx !== 'undefined' && wx.cloud) {
        console.log('正在初始化云开发，环境ID:', CLOUD_CONFIG.envId)
        
        wx.cloud.init({
          env: CLOUD_CONFIG.envId,
          traceUser: true
        })
        
        this.db = wx.cloud.database()
        console.log('云开发初始化成功')
        
        // 测试数据库连接 - 使用更高效的查询方式
        try {
          // 使用count()方法替代limit(1).get()来避免全表扫描
          await this.db.collection(CLOUD_CONFIG.collections.rooms).count()
          console.log('数据库连接测试成功')
        } catch (dbError) {
          console.error('数据库连接测试失败:', dbError)
          throw new Error('数据库连接失败，请检查云环境配置')
        }
      } else {
        console.warn('云开发不可用')
        throw new Error('云开发不可用')
      }
    } catch (error) {
      console.error('云开发初始化失败:', error)
      throw error
    }
  }

  // 生成房间ID
  generateRoomId() {
    return 'room_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
  }

  // 创建房间
  async createRoom() {
    try {
      console.log('创建房间...')
      
      // 确保云开发已初始化
      if (!this.db) {
        console.log('云开发未初始化，重新初始化...')
        await this.initCloud()
      }
      
      const openId = await this.getOpenId()
      const roomId = this.generateRoomId()
      
      console.log('创建房间参数:', { openId, roomId })
      
      // 验证OpenID是否有效
      if (!openId || openId === 'undefined' || openId === 'null') {
        throw new Error('获取到的OpenID无效: ' + openId)
      }
      
      // 创建房间记录
      const roomData = {
        roomId: roomId,
        player1: openId, // 房主（白子）
        player2: null,
        status: 'waiting',
        chessboard: this.createEmptyBoard(),
        currentPlayer: null, // 等待第二个玩家加入后设置
        lastMove: null,
        winner: null,
        createTime: new Date(),
        lastUpdate: new Date(),
        gameStartTime: null // 游戏开始时间，加入者设置
      }
      
      console.log('准备创建房间数据:', roomData)
      
      const result = await this.db.collection(CLOUD_CONFIG.collections.rooms).add({
        data: roomData
      })
      
      console.log('房间创建结果:', result)
      
      this.roomId = roomId
      this.playerId = openId
      this.isCreator = true
      this.gameStarted = false
      this.watchRetryCount = 0
      
      console.log('房间创建成功:', roomId)
      
      // 开始监听房间变化
      this.watchRoom()
      
      // 为房间创建者添加定期检查机制
      if (this.isCreator) {
        console.log('为房间创建者设置定期检查')
        this.startPeriodicCheck()
        
        // 为创建者添加额外的游戏开始检查
        setTimeout(() => {
          this.checkRoomStatus()
        }, 1000)
        
        // 定期检查是否有玩家加入
        setTimeout(() => {
          this.checkRoomStatus()
        }, 3000)
      }
      
      if (this.onRoomCreated) {
        this.onRoomCreated(roomId, true)
      }
      
      return roomId
    } catch (error) {
      console.error('创建房间失败:', error)
      
      // 如果是认证错误，尝试重新初始化
      if (error.errCode === -402002 || error.errMsg.includes('login fail')) {
        console.log('创建房间时遇到认证错误，尝试重新初始化...')
        try {
          await this.initCloud()
          // 重试创建房间
          return await this.createRoom()
        } catch (retryError) {
          console.error('重试创建房间失败:', retryError)
          throw retryError
        }
      }
      
      throw error
    }
  }

  // 加入房间
  async joinRoom(roomId) {
    try {
      console.log('准备加入房间:', roomId)
      
      // 获取用户OpenID
      const openId = await this.getOpenId()
      if (!openId) {
        throw new Error('获取用户OpenID失败')
      }
      console.log('用户OpenID:', openId)
      
      // 验证房间是否存在
      const roomInfo = await this.validateRoom(roomId)
      if (!roomInfo.exists || !roomInfo.room) {
        throw new Error('房间不存在或已满')
      }
      
      const room = roomInfo.room
      const roomDocId = room._id
      console.log('准备更新房间，文档ID:', roomDocId)
      
      // 检查房间状态
      if (room.status !== 'waiting') {
        throw new Error('房间已满或游戏已开始')
      }
      
      // 检查是否是自己创建的房间
      if (room.player1 === openId) {
        throw new Error('不能加入自己创建的房间')
      }
      
      // 检查房间是否已经有player2
      if (room.player2) {
        throw new Error('房间已满，无法加入')
      }
      
      // 更新房间数据 - 使用事务确保数据一致性
      const updateData = {
        player2: openId, // 加入者（黑子）
        status: 'playing',
        currentPlayer: openId, // 黑子先手
        lastUpdate: new Date(),
        gameStartTime: new Date() // 添加游戏开始时间
      }
      console.log('更新数据:', updateData)
      
      // 执行更新操作 - 增强版本
      let updateSuccess = false
      let retryCount = 0
      const maxRetries = 5
      let updateResult
      
      while (!updateSuccess && retryCount < maxRetries) {
        try {
          // 先获取最新数据，确保数据一致性
          const latestRoom = await this.db.collection(CLOUD_CONFIG.collections.rooms)
            .doc(roomDocId)
            .get()
          
          const currentRoom = latestRoom.data
          console.log(`更新前房间状态 (尝试 ${retryCount + 1}/${maxRetries}):`, {
            status: currentRoom.status,
            player1: currentRoom.player1,
            player2: currentRoom.player2
          })
          
          // 检查房间状态是否仍然可用
          if (currentRoom.status !== 'waiting') {
            throw new Error('房间状态已改变，无法加入')
          }
          
          // 检查是否已经有player2
          if (currentRoom.player2) {
            throw new Error('房间已被其他玩家加入')
          }
          
          // 使用事务更新，确保数据一致性
          updateResult = await this.db.collection(CLOUD_CONFIG.collections.rooms).doc(roomDocId).update({
            data: updateData
          })
          
          console.log(`房间更新结果 (尝试 ${retryCount + 1}/${maxRetries}):`, updateResult)
          updateSuccess = true
        } catch (updateError) {
          retryCount++
          console.error(`房间更新失败 (尝试 ${retryCount}/${maxRetries}):`, updateError)
          
          if (retryCount >= maxRetries) {
            throw new Error(`房间更新失败，已重试 ${maxRetries} 次: ${updateError.message}`)
          }
          
          // 等待一段时间后重试
          await new Promise(resolve => setTimeout(resolve, 1000 * retryCount))
        }
      }
      
      console.log('房间状态已更新为playing，开始验证更新...')
      
      // 使用轮询机制验证更新是否成功 - 增强版本
      const maxVerificationAttempts = 15
      let verificationAttempts = 0
      let verificationSuccess = false
      
      const verifyUpdate = async () => {
        try {
          const verifyResult = await this.db.collection(CLOUD_CONFIG.collections.rooms)
            .doc(roomDocId)
            .get()
          
          const updatedRoom = verifyResult.data
          console.log(`验证尝试 ${verificationAttempts + 1}/${maxVerificationAttempts}:`, {
            status: updatedRoom.status,
            player1: updatedRoom.player1,
            player2: updatedRoom.player2,
            currentPlayer: updatedRoom.currentPlayer,
            gameStartTime: updatedRoom.gameStartTime
          })
          
          if (updatedRoom.player2 === openId && updatedRoom.status === 'playing') {
            console.log('✅ 房间更新验证成功')
            verificationSuccess = true
            return true
          } else {
            console.log('❌ 房间更新验证失败，继续等待...')
            return false
          }
        } catch (verifyError) {
          console.error('验证失败:', verifyError)
          return false
        }
      }
      
      // 立即验证一次
      if (await verifyUpdate()) {
        verificationSuccess = true
      } else {
        // 如果立即验证失败，开始轮询验证
        console.log('立即验证失败，开始轮询验证...')
        
        while (!verificationSuccess && verificationAttempts < maxVerificationAttempts) {
          verificationAttempts++
          await new Promise(resolve => setTimeout(resolve, 800)) // 缩短等待时间到800ms
          
          if (await verifyUpdate()) {
            verificationSuccess = true
            break
          }
        }
      }
      
      if (!verificationSuccess) {
        console.error('❌ 房间更新验证失败，已达到最大尝试次数')
        throw new Error('房间更新验证失败：player2未正确设置')
      }
      
      // 设置本地状态
      this.roomId = roomId
      this.playerId = openId
      this.isCreator = false
      this.gameStarted = false
      this.watchRetryCount = 0
      
      console.log('成功加入房间:', roomId)
      
      // 触发房间加入回调
      if (this.onRoomJoined) {
        console.log('触发房间加入回调')
        this.onRoomJoined(roomId, false)
      }
      
      // 开始监听房间变化
      this.watchRoom()
      
      // 立即触发房间状态检查，确保游戏开始
      setTimeout(() => {
        this.checkRoomStatus()
      }, 500)
      
      // 额外检查：确保双方都能检测到游戏开始
      setTimeout(() => {
        this.forceGameStart()
      }, 2000)
      
      return roomId
    } catch (error) {
      console.error('加入房间失败:', error)
      throw error
    }
  }

  // 验证房间是否存在
  async validateRoom(roomId) {
    try {
      console.log('验证房间:', roomId)
      
      const roomResult = await this.db.collection(CLOUD_CONFIG.collections.rooms)
        .where({
          roomId: roomId
        })
        .get()
      
      console.log('房间查询结果:', roomResult)
      
      if (roomResult.data.length === 0) {
        console.log('房间不存在')
        return { exists: false, room: null }
      }
      
      const room = roomResult.data[0]
      console.log('找到房间:', {
        _id: room._id,
        roomId: room.roomId,
        status: room.status,
        player1: room.player1,
        player2: room.player2
      })
      
      return { exists: true, room: room }
    } catch (error) {
      console.error('验证房间失败:', error)
      return { exists: false, room: null }
    }
  }

  // 监听房间变化 - 增强版本
  watchRoom() {
    if (!this.db || !this.roomId) {
      console.error('无法监听房间：数据库或房间ID未初始化')
      return
    }

    try {
      console.log('开始监听房间变化:', this.roomId)
      
      // 先关闭之前的监听器
      if (this.roomWatcher) {
        try {
          this.roomWatcher.close()
          console.log('关闭之前的房间监听器')
        } catch (closeError) {
          console.warn('关闭之前的监听器失败:', closeError)
        }
      }
      
      // 重置重试计数
      this.watchRetryCount = 0
      
      this.roomWatcher = this.db.collection(CLOUD_CONFIG.collections.rooms)
        .where({
          roomId: this.roomId
        })
        .watch({
          onChange: (snapshot) => {
            console.log('房间变化监听触发:', snapshot)
            if (snapshot.docs.length > 0) {
              const room = snapshot.docs[0]
              console.log('房间数据更新:', room)
              console.log('当前游戏状态:', {
                gameStarted: this.gameStarted,
                isCreator: this.isCreator,
                playerId: this.playerId
              })
              this.handleRoomUpdate(room)
            } else {
              console.log('房间变化监听触发，但没有找到房间数据')
            }
          },
          onError: (error) => {
            console.error('房间监听错误:', error)
            
            // 处理WebSocket连接错误
            if (this.handleWatchError(error)) {
              return
            }
            
            // 如果是认证错误，尝试重新初始化云开发
            if (error.errCode === -402002 || error.errMsg.includes('login fail')) {
              console.log('检测到认证错误，尝试重新初始化云开发...')
              this.retryWatchRoom()
            }
          }
        })
      
      console.log('房间监听设置成功')
    } catch (error) {
      console.error('开始监听房间失败:', error)
      
      // 处理WebSocket连接错误
      if (this.handleWatchError(error)) {
        return
      }
      
      // 如果是认证相关错误，尝试重新初始化
      if (error.errCode === -402002 || error.errMsg.includes('login fail')) {
        console.log('监听失败，尝试重新初始化...')
        this.retryWatchRoom()
      }
    }
  }

  // 处理监听错误
  handleWatchError(error) {
    const errorMsg = error.message || error.errMsg || ''
    
    // 检查是否是WebSocket连接问题
    if (errorMsg.includes('ws connection not exists') || 
        errorMsg.includes('invalid state') ||
        errorMsg.includes('connection not exists')) {
      
      console.log('检测到WebSocket连接问题，切换到轮询模式')
      
      // 显示用户友好的错误提示
      if (typeof wx !== 'undefined' && wx.showToast) {
        wx.showToast({
          title: '连接不稳定，已切换到轮询模式',
          icon: 'none',
          duration: 2000
        })
      }
      
      // 停止监听，改用轮询
      this.stopWatching()
      this.startPollingMode()
      return true
    }
    
    return false
  }

  // 停止监听
  stopWatching() {
    if (this.roomWatcher) {
      try {
        this.roomWatcher.close()
        console.log('停止房间监听')
      } catch (error) {
        console.warn('停止监听失败:', error)
      }
      this.roomWatcher = null
    }
  }

  // 启动轮询模式
  startPollingMode() {
    console.log('启动轮询模式')
    
    // 更频繁的检查
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer)
    }
    
    this.pollingTimer = setInterval(() => {
      if (this.gameStarted) {
        console.log('游戏已开始，停止轮询')
        this.stopPollingMode()
        return
      }
      
      console.log('轮询检查房间状态...')
      this.checkRoomStatus()
    }, 2000) // 每2秒检查一次
  }

  // 停止轮询模式
  stopPollingMode() {
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer)
      this.pollingTimer = null
      console.log('停止轮询模式')
    }
  }

  // 重试监听房间
  async retryWatchRoom() {
    try {
      this.watchRetryCount++
      
      if (this.watchRetryCount > this.maxWatchRetries) {
        console.log('监听重试次数超过限制，切换到轮询模式')
        this.stopWatching()
        this.startPollingMode()
        return
      }
      
      console.log(`重试监听房间 (${this.watchRetryCount}/${this.maxWatchRetries})...`)
      
      // 等待一段时间后重试
      await new Promise(resolve => setTimeout(resolve, 2000 * this.watchRetryCount))
      
      // 重新初始化云开发
      await this.initCloud()
      
      // 重新开始监听
      this.watchRoom()
    } catch (error) {
      console.error('重试监听房间失败:', error)
      
      // 如果重试失败，切换到轮询模式
      if (this.watchRetryCount >= this.maxWatchRetries) {
        console.log('重试失败，切换到轮询模式')
        this.stopWatching()
        this.startPollingMode()
      }
    }
  }

  // 检查云环境配置
  async checkCloudEnvironment() {
    try {
      console.log('检查云环境配置...')
      
      // 检查云开发是否可用
      if (typeof wx === 'undefined' || !wx.cloud) {
        throw new Error('云开发不可用')
      }
      
      // 检查数据库连接
      if (!this.db) {
        await this.initCloud()
      }
      
      // 测试数据库操作 - 使用更高效的查询方式
      const testResult = await this.db.collection(CLOUD_CONFIG.collections.rooms).count()
      console.log('云环境检查通过，房间总数:', testResult.total)
      
      return true
    } catch (error) {
      console.error('云环境检查失败:', error)
      
      // 显示详细的错误信息
      let errorMessage = '云环境配置错误'
      if (error.errCode === -402002) {
        errorMessage = '云环境认证失败，请检查环境ID配置'
      } else if (error.message.includes('login fail')) {
        errorMessage = '云环境登录失败，请检查网络连接'
      } else if (error.message.includes('云开发不可用')) {
        errorMessage = '云开发功能不可用，请检查小程序配置'
      }
      
      if (typeof wx !== 'undefined' && wx.showModal) {
        wx.showModal({
          title: '连接错误',
          content: errorMessage + '\n\n请检查：\n1. 云环境ID是否正确\n2. 网络连接是否正常\n3. 小程序是否已开通云开发',
          showCancel: false
        })
      }
      
      return false
    }
  }

  // 处理房间更新
  handleRoomUpdate(room) {
    if (!room) return
    
    console.log('房间状态更新:', {
      roomId: room.roomId,
      status: room.status,
      player1: room.player1,
      player2: room.player2,
      currentPlayer: room.currentPlayer,
      gameStartTime: room.gameStartTime,
      lastUpdate: room.lastUpdate
    })
    
    // 检查游戏是否开始 - 两个玩家都已连接且状态为playing
    if (room.status === 'playing' && room.player1 && room.player2) {
      console.log('检测到游戏开始条件:', {
        status: room.status,
        player1: room.player1,
        player2: room.player2,
        currentPlayer: room.currentPlayer,
        gameStartTime: room.gameStartTime,
        myPlayerId: this.playerId,
        gameStarted: this.gameStarted
      })
      
      // 防止重复触发游戏开始
      if (!this.gameStarted) {
        this.gameStarted = true
        console.log('设置游戏开始标志为true')
        
        // 两个玩家都已连接，开始游戏
        if (this.onGameStart) {
          console.log('触发游戏开始回调')
          this.onGameStart()
        }
        
        // 通知对手连接
        if (this.onOpponentConnected) {
          console.log('触发对手连接回调')
          this.onOpponentConnected()
        }
        
        // 停止定期检查（如果正在运行）
        this.stopPeriodicCheck()
      } else {
        console.log('游戏已经开始，跳过重复触发')
      }
      
      // 更新棋盘状态
      if (room.chessboard) {
        this.currentChessboard = room.chessboard
        console.log('更新棋盘状态')
      }
      
      // 设置当前玩家
      if (room.currentPlayer) {
        this.currentPlayer = room.currentPlayer
        console.log('设置当前玩家:', room.currentPlayer)
        
        // 通知DataBus更新回合状态
        if (this.onMoveReceived) {
          this.onMoveReceived(room.chessboard, room.currentPlayer)
        }
      }
    } else {
      console.log('游戏开始条件不满足:', {
        status: room.status,
        player1: room.player1,
        player2: room.player2,
        gameStarted: this.gameStarted
      })
      
      // 如果房间状态是waiting但已有两个玩家，可能是数据同步问题
      if (room.status === 'waiting' && room.player1 && room.player2) {
        console.log('检测到数据同步问题：房间状态为waiting但已有两个玩家')
        // 强制更新状态
        this.forceUpdateRoomStatus(room._id, 'playing', room.player2)
      }
      
      // 如果房间状态是playing但缺少player2，可能是数据不一致
      if (room.status === 'playing' && room.player1 && !room.player2) {
        console.log('检测到数据不一致：房间状态为playing但缺少player2')
        // 强制更新状态为waiting
        this.forceUpdateRoomStatus(room._id, 'waiting', null)
      }
    }
    
    // 检查游戏是否结束
    if (room.status === 'finished' && room.winner) {
      console.log('游戏结束，获胜者:', room.winner)
      if (this.onGameOver) {
        this.onGameOver(room.winner)
      }
    }
    
    // 检查是否有新的落子
    if (room.lastMove && room.lastMove.row !== undefined && room.lastMove.col !== undefined) {
      const lastMove = room.lastMove
      console.log('检测到新落子:', lastMove)
      if (lastMove.player !== this.playerId) {
        // 对手的落子
        console.log('处理对手落子')
        if (this.onMoveReceived) {
          this.onMoveReceived(room.chessboard, room.currentPlayer)
        }
      }
    }
  }

  // 落子
  async makeMove(row, col) {
    try {
      if (!this.roomId) {
        throw new Error('未在房间中')
      }
      
      // 通过roomId字段查找房间
      const roomResult = await this.db.collection(CLOUD_CONFIG.collections.rooms)
        .where({
          roomId: this.roomId
        })
        .get()
      
      if (roomResult.data.length === 0) {
        throw new Error('房间不存在')
      }
      
      const room = roomResult.data[0]
      const roomDocId = room._id // 获取文档的实际ID
      
      // 检查是否轮到当前玩家
      if (room.currentPlayer !== this.playerId) {
        throw new Error('不是你的回合')
      }
      
      // 检查位置是否有效
      if (row < 0 || row >= 15 || col < 0 || col >= 15) {
        throw new Error('无效的位置')
      }
      
      // 检查位置是否已被占用
      if (room.chessboard[row][col] !== 0) {
        throw new Error('该位置已有棋子')
      }
      
      // 更新棋盘
      const newChessboard = JSON.parse(JSON.stringify(room.chessboard))
      // 房主是白子(2)，加入者是黑子(1)
      const playerValue = this.playerId === room.player1 ? 2 : 1
      newChessboard[row][col] = playerValue
      
      // 检查是否获胜
      const isWin = this.checkWin(newChessboard, row, col, playerValue)
      
      // 确定下一个玩家（房主是白子，加入者是黑子）
      const nextPlayer = this.playerId === room.player1 ? room.player2 : room.player1
      
      // 更新房间状态
      const updateData = {
        chessboard: newChessboard,
        currentPlayer: nextPlayer,
        lastMove: {
          row: row,
          col: col,
          player: this.playerId
        },
        lastUpdate: new Date()
      }
      
      if (isWin) {
        updateData.status = 'finished'
        updateData.winner = this.playerId
      }
      
      // 使用文档ID更新房间
      await this.db.collection(CLOUD_CONFIG.collections.rooms).doc(roomDocId).update({
        data: updateData
      })
      
      console.log('落子成功:', { row, col, player: this.playerId })
      return true
    } catch (error) {
      console.error('落子失败:', error)
      throw error
    }
  }

  // 检查获胜
  checkWin(chessboard, row, col, player) {
    const directions = [
      [[0, 1], [0, -1]], // 水平
      [[1, 0], [-1, 0]], // 垂直
      [[1, 1], [-1, -1]], // 主对角线
      [[1, -1], [-1, 1]] // 副对角线
    ]

    for (const direction of directions) {
      let count = 1
      
      for (const [dx, dy] of direction) {
        let x = row + dx
        let y = col + dy
        
        while (
          x >= 0 && x < 15 && 
          y >= 0 && y < 15 && 
          chessboard[x][y] === player
        ) {
          count++
          x += dx
          y += dy
        }
      }
      
      if (count >= 5) {
        return true
      }
    }
    
    return false
  }

  // 创建空棋盘
  createEmptyBoard() {
    return Array(15).fill().map(() => Array(15).fill(0))
  }

  // 获取用户OpenID
  async getOpenId() {
    // 如果已有缓存的OpenID，直接返回
    if (this.cachedOpenId) {
      console.log('使用缓存的OpenID:', this.cachedOpenId)
      return this.cachedOpenId
    }
    
    console.log('正在获取OpenID...')
    
    // 暂时跳过云函数，直接使用备选方案（因为云函数部署有问题）
    console.log('跳过云函数，直接使用备选方案...')
    
    // 备选方案1：使用微信登录
    try {
      console.log('尝试通过wx.login获取用户信息...')
      const loginResult = await wx.login()
      
      if (loginResult && loginResult.code) {
        // 使用登录code生成唯一ID
        this.cachedOpenId = 'login_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        console.log('✅ 使用登录code生成临时ID:', this.cachedOpenId)
        return this.cachedOpenId
      }
    } catch (loginError) {
      console.error('wx.login失败:', loginError)
    }
    
    // 备选方案2：使用系统信息生成唯一ID
    try {
      console.log('尝试获取系统信息...')
      const systemInfo = wx.getSystemInfoSync()
      this.cachedOpenId = 'device_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
      console.log('✅ 使用设备信息生成ID:', this.cachedOpenId, '系统信息:', systemInfo.platform)
      return this.cachedOpenId
    } catch (systemError) {
      console.error('获取系统信息失败:', systemError)
    }
    
    // 最后的备选方案：使用时间戳生成唯一ID
    this.cachedOpenId = 'fallback_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
    console.log('✅ 使用备选方案生成ID:', this.cachedOpenId)
    return this.cachedOpenId
  }

  // 生成分享链接
  getShareLink() {
    if (!this.roomId) return null
    
    return {
      title: '来和我下五子棋吧！',
      path: `/pages/game?roomId=${this.roomId}`,
      imageUrl: '/images/share.jpg' // 需要添加分享图片
    }
  }

  // 清理资源
  cleanup() {
    if (this.roomWatcher) {
      this.roomWatcher.close()
      this.roomWatcher = null
    }
    
    // 停止定期检查
    this.stopPeriodicCheck()
    
    // 停止轮询
    this.stopPollingMode()
    
    this.roomId = null
    this.playerId = null
    this.isCreator = false
    this.gameStarted = false
    this.opponentConnected = false
    this.watchRetryCount = 0
    this.cachedOpenId = null // 清除缓存的OpenID
  }

  // 开始定期检查房间状态
  startPeriodicCheck() {
    if (this.periodicCheckTimer) {
      clearInterval(this.periodicCheckTimer)
    }
    
    this.periodicCheckTimer = setInterval(() => {
      if (this.gameStarted) {
        // 游戏已开始，停止定期检查
        console.log('游戏已开始，停止定期检查')
        this.stopPeriodicCheck()
        return
      }
      
      console.log('定期检查房间状态...')
      this.checkRoomStatus()
    }, 1000) // 每1秒检查一次（更频繁）
  }
  
  // 停止定期检查
  stopPeriodicCheck() {
    if (this.periodicCheckTimer) {
      clearInterval(this.periodicCheckTimer)
      this.periodicCheckTimer = null
      console.log('停止定期检查')
    }
  }
  
  // 手动检查房间状态
  async checkRoomStatus() {
    try {
      if (!this.roomId) return
      
      console.log('手动检查房间状态:', this.roomId)
      
      const roomResult = await this.db.collection(CLOUD_CONFIG.collections.rooms)
        .where({
          roomId: this.roomId
        })
        .get()
      
      if (roomResult.data.length > 0) {
        const room = roomResult.data[0]
        console.log('手动检查房间状态结果:', room)
        
        // 检查回调函数状态
        console.log('回调函数状态:', {
          onGameStart: !!this.onGameStart,
          onOpponentConnected: !!this.onOpponentConnected,
          onRoomCreated: !!this.onRoomCreated,
          onRoomJoined: !!this.onRoomJoined
        })
        
        // 检查是否满足游戏开始条件
        if (room.status === 'playing' && room.player1 && room.player2) {
          console.log('手动检查发现游戏开始条件满足')
          console.log('手动检查时的游戏状态:', {
            gameStarted: this.gameStarted,
            isCreator: this.isCreator,
            playerId: this.playerId
          })
          this.handleRoomUpdate(room)
        } else {
          console.log('手动检查发现游戏开始条件不满足:', {
            status: room.status,
            player1: room.player1,
            player2: room.player2
          })
          
          // 如果是创建者，检查是否需要强制更新状态
          if (this.isCreator) {
            if (room.status === 'waiting' && room.player1 && !room.player2) {
              console.log('创建者检测到player2仍为null，等待加入者...')
            } else if (room.status === 'playing' && room.player1 && room.player2) {
              console.log('创建者检测到player2已设置，应该开始游戏')
              this.handleRoomUpdate(room)
            } else if (room.status === 'waiting' && room.player1 && room.player2) {
              // 如果player2已设置但状态还是waiting，强制更新状态
              console.log('创建者检测到player2已设置但状态仍为waiting，强制更新状态')
              try {
                await this.db.collection(CLOUD_CONFIG.collections.rooms)
                  .doc(room._id)
                  .update({
                    data: {
                      status: 'playing',
                      currentPlayer: room.player2, // 黑子先手
                      lastUpdate: new Date()
                    }
                  })
                console.log('✅ 强制更新房间状态成功')
                // 重新检查房间状态
                setTimeout(() => {
                  this.checkRoomStatus()
                }, 500)
              } catch (forceUpdateError) {
                console.error('强制更新房间状态失败:', forceUpdateError)
              }
            } else if (room.status === 'playing' && room.player1 && !room.player2) {
              // 如果状态是playing但没有player2，可能是数据不一致
              console.log('创建者检测到数据不一致：状态为playing但没有player2')
              try {
                await this.db.collection(CLOUD_CONFIG.collections.rooms)
                  .doc(room._id)
                  .update({
                    data: {
                      status: 'waiting',
                      currentPlayer: null,
                      lastUpdate: new Date()
                    }
                  })
                console.log('✅ 修正房间状态为waiting')
              } catch (fixError) {
                console.error('修正房间状态失败:', fixError)
              }
            }
          }
          
          // 如果是加入者，检查是否需要通知创建者
          if (!this.isCreator && room.status === 'playing' && room.player1 && room.player2) {
            console.log('加入者检测到游戏条件满足，触发游戏开始')
            this.handleRoomUpdate(room)
          }
        }
      } else {
        console.log('手动检查未找到房间')
      }
    } catch (error) {
      console.error('手动检查房间状态失败:', error)
    }
  }

  // 强制更新房间状态
  async forceUpdateRoomStatus(roomDocId, status, currentPlayer) {
    try {
      console.log('强制更新房间状态:', { roomDocId, status, currentPlayer })
      
      // 先验证房间是否存在
      const roomCheck = await this.db.collection(CLOUD_CONFIG.collections.rooms)
        .doc(roomDocId)
        .get()
      
      if (!roomCheck.data) {
        console.error('房间不存在，无法强制更新状态')
        return
      }
      
      const currentRoom = roomCheck.data
      console.log('当前房间状态:', {
        status: currentRoom.status,
        player1: currentRoom.player1,
        player2: currentRoom.player2,
        currentPlayer: currentRoom.currentPlayer
      })
      
      // 构建更新数据
      const updateData = {
        status: status,
        lastUpdate: new Date()
      }
      
      // 只有在明确指定currentPlayer时才更新
      if (currentPlayer !== null && currentPlayer !== undefined) {
        updateData.currentPlayer = currentPlayer
      }
      
      await this.db.collection(CLOUD_CONFIG.collections.rooms)
        .doc(roomDocId)
        .update({
          data: updateData
        })
      
      console.log('✅ 强制更新房间状态成功')
      
      // 验证更新是否成功
      setTimeout(async () => {
        try {
          const verifyResult = await this.db.collection(CLOUD_CONFIG.collections.rooms)
            .doc(roomDocId)
            .get()
          
          const updatedRoom = verifyResult.data
          console.log('强制更新验证结果:', {
            status: updatedRoom.status,
            currentPlayer: updatedRoom.currentPlayer,
            lastUpdate: updatedRoom.lastUpdate
          })
        } catch (verifyError) {
          console.error('强制更新验证失败:', verifyError)
        }
      }, 500)
      
    } catch (error) {
      console.error('强制更新房间状态失败:', error)
    }
  }

  // 强制游戏开始 - 确保双方都能检测到游戏开始
  async forceGameStart() {
    if (!this.roomId || this.gameStarted) return
    
    try {
      console.log('执行强制游戏开始检查...')
      
      const roomResult = await this.db.collection(CLOUD_CONFIG.collections.rooms)
        .where({
          roomId: this.roomId
        })
        .get()
      
      if (roomResult.data.length > 0) {
        const room = roomResult.data[0]
        
        // 检查是否满足游戏开始条件
        if (room.status === 'playing' && room.player1 && room.player2) {
          console.log('强制游戏开始：满足条件', {
            status: room.status,
            player1: room.player1,
            player2: room.player2,
            currentPlayer: room.currentPlayer
          })
          
          // 手动触发游戏开始
          if (!this.gameStarted) {
            this.gameStarted = true
            console.log('强制设置游戏开始标志为true')
            
            if (this.onGameStart) {
              console.log('强制触发游戏开始回调')
              this.onGameStart()
            }
            
            if (this.onOpponentConnected) {
              console.log('强制触发对手连接回调')
              this.onOpponentConnected()
            }
          }
        } else {
          console.log('强制游戏开始：条件不满足', {
            status: room.status,
            player1: room.player1,
            player2: room.player2
          })
        }
      }
    } catch (error) {
      console.error('强制游戏开始检查失败:', error)
    }
  }
} 